<template>
  <div class="app-container">
    <div class="search-bar">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="生产日期" prop="code">
          <el-date-picker
            v-model="queryParams.planDate"
            type="date"
            placeholder="计划开始日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            class="!w-[192px]"
            clearable
            @change="handleQuery"
          />
        </el-form-item>

        <el-form-item label="生产完成日期" prop="code">
          <el-date-picker
            v-model="queryParams.finishTime"
            type="date"
            placeholder="生产完成日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            class="!w-[192px]"
            clearable
            @change="handleQuery"
          />
        </el-form-item>

        <el-form-item label="产品名称" prop="productCode">
          <el-select
            v-model="queryParams.productCode"
            placeholder="请选择产品名称"
            class="!w-[192px]"
            clearable
            filterable
            @visible-change="getProductType"
            @change="handleQuery"
          >
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="生产状态" prop="productCode">
          <el-select
            v-model="queryParams.status"
            placeholder="生产状态"
            class="!w-[192px]"
            filterable
            clearable
            @change="handleQuery"
          >
            <el-option
              v-for="item in filteredStatusList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
          <el-button icon="refresh" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-card shadow="never">
      <!-- 标题与状态统计 -->
      <!-- <div class="flex items-center justify-between mb-6">
        <div class="flex items-center gap-6">
          <div class="flex items-center gap-2">
            <el-text class="w-2 h-2 rounded-full bg-green-500" />
            <el-text>审核通过: {{ stats.approved }}</el-text>
          </div>
          <div class="flex items-center gap-2">
            <el-text class="w-2 h-2 rounded-full bg-blue-500" />
            <el-text>准备中: {{ stats.preparing }}</el-text>
          </div>
          <div class="flex items-center gap-2">
            <el-text class="w-2 h-2 rounded-full bg-yellow-500" />
            <el-text>待生产: {{ stats.pending }}</el-text>
          </div>
          <div class="flex items-center gap-2">
            <el-text class="w-2 h-2 rounded-full bg-purple-500" />
            <el-text>生产中: {{ stats.inProgress }}</el-text>
          </div>
          <div class="flex items-center gap-2">
            <el-text class="w-2 h-2 rounded-full bg-gray-500" />
            <el-text>生产完成: {{ stats.completed }}</el-text>
          </div>
        </div>
      </div> -->

      <!-- 搜索区域 -->

      <!-- 表格区域 -->
      <el-table v-loading="loading" :data="tableData" style="width: 100%">
        <el-table-column prop="code" label="生产单号" align="center" min-width="120" />
        <el-table-column label="产品信息" align="center">
          <template #default="scope">
            <div>
              <div>{{ scope.row.productName }}</div>
              <!-- <el-text size="small" class="text-gray-500 text-sm">
                需求数量: {{ scope.row.qty }}{{ unitFormat(scope.row.unit) }}
              </el-text> -->
            </div>
          </template>
        </el-table-column>
        <el-table-column label="生产状态" align="center">
          <template #default="scope">
            <el-tag v-if="scope.row.status == 1" type="success">已确认</el-tag>

            <el-tag v-if="scope.row.status == 3" type="info">准备中</el-tag>
            <el-tag v-if="scope.row.status == 4" type="warning">待生产</el-tag>
            <el-tag v-if="scope.row.status == 5" type="warning">生产中</el-tag>
            <el-tag v-if="scope.row.status == 6" type="success">生产完成</el-tag>
            <el-tag v-if="scope.row.status == 7" type="danger">暂停</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="planDate" label="生产日期" align="center" show-overflow-tooltip />
        <el-table-column prop="startTime" label="开始时间" align="center" show-overflow-tooltip>
          <template #default="scope">{{ scope.row.startTime || "--" }}</template>
        </el-table-column>
        <el-table-column prop="finishTime" label="完成时间" align="center" show-overflow-tooltip>
          <template #default="scope">{{ scope.row.finishTime || "--" }}</template>
        </el-table-column>
        <!-- <el-table-column label="计划信息" align="center">
          <template #default="scope">
            <div>
              <el-text size="small">开始时间: {{ scope.row.startTime || "--" }}</el-text>
            </div>
            <div>
              <el-text size="small">完成时间: {{ scope.row.finishTime || "--" }}</el-text>
            </div>
          </template>
        </el-table-column> -->
        <el-table-column prop="remark" label="备注" align="center" show-overflow-tooltip />
        <el-table-column label="进度" align="center">
          <template #default="scope">
            <div>
              <el-progress :percentage="scope.row.progress" />
              <div class="mt-1">
                <div>
                  <el-text size="small">
                    需要生产: {{ scope.row.qty || 0 }}{{ unitFormat(scope.row.unit) }}
                  </el-text>
                </div>
                <!-- <div>
                  <el-text class="ml-2" size="small">
                    原料消耗: {{ scope.row.dosageQty || 0 }}{{ unitFormat(scope.row.unit) }}
                  </el-text>
                </div> -->
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240" align="center">
          <template #default="scope">
            <!-- v-if="scope.row.status === 5" -->
            <el-button
              link
              type="primary"
              size="small"
              class="!rounded-button"
              v-if="scope.row.status === 5"
              @click="handlePause(scope.row)"
              v-hasPerm="'sys:prodOrderManage:prod'"
            >
              暂停
            </el-button>
            <el-button
              v-hasPerm="'sys:prodOrderManage:prod'"
              link
              type="primary"
              size="small"
              class="!rounded-button"
              v-if="scope.row.status === 7"
              @click="handlePause(scope.row)"
            >
              恢复生产
            </el-button>
            <el-button
              link
              type="primary"
              size="small"
              class="!rounded-button"
              @click="handleOpenDetail(scope.row)"
            >
              查看
            </el-button>

            <el-button
              v-hasPerm="'sys:prodOrderManage:prod'"
              v-if="scope.row.status !== 3 && scope.row.status !== 6"
              link
              :type="getStatusType(scope.row.status)"
              size="small"
              class="!rounded-button"
              @click="handleStartProduce(scope.row)"
            >
              {{
                // scope.row.status ===1 "开始备料" scope.row.status ===3 ""  scope.row.status ===4 "开始生产"  scope.row.status ===5 "强制完成" scope.row.status ===6 ""
                scope.row.status === 1
                  ? "开始备料"
                  : scope.row.status === 4
                    ? "开始生产"
                    : scope.row.status === 5
                      ? "完成"
                      : ""
              }}
            </el-button>
            <el-button
              link
              type="primary"
              size="small"
              class="!rounded-button"
              @click="handleOpenInspection(scope.row)"
            >
              质检记录
            </el-button>
            <!-- <el-button
              link
              type="primary"
              size="small"
              class="!rounded-button"
              @click="handleDelete(scope.row.id)"
              v-if="scope.row.status < 5"
            >
              取消
            </el-button> -->
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </el-card>
    <!-- 查看详情弹窗 -->

    <el-dialog v-model="dialogVisible" @close="handleCloseDialog" title="生产单详情" width="60%">
      <el-row style="padding: 0 20px">
        <el-col :span="6">产品编号:{{ rowObj?.prodHead?.productCode }}</el-col>
        <el-col :span="6">产品名称:{{ rowObj?.prodHead?.productName }}</el-col>
        <el-col :span="6">生产日期:{{ rowObj?.prodHead?.planDate }}</el-col>
        <el-col :span="6">
          生产数量:{{ rowObj?.prodHead?.qty }}{{ unitFormat(rowObj?.prodHead?.unit) }}
        </el-col>
      </el-row>
      <el-row class="mt-8">
        <el-col :span="24">
          <el-tabs tab-position="left" class="demo-tabs" v-model="tabActive">
            <el-tab-pane label="工序维护">
              <el-row>
                <div class="draggable" style="width: 100%">
                  <el-table :data="rowData" row-key="id" class="w100">
                    <el-table-column type="index" label="生产顺序" align="center" width="100" />
                    <el-table-column prop="processName" label="工序名称" align="center" />
                    <el-table-column label="当前生产单工序产能" align="center" width="300">
                      <template #default="scope">
                        <el-text>{{ scope.row.capacity }}</el-text>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </el-row>
            </el-tab-pane>
            <el-tab-pane label="生产日期">
              <p>计划生产日期</p>
              <el-text>
                {{ rowObj?.prodHead?.planDate }}
              </el-text>
            </el-tab-pane>
            <el-tab-pane label="原材料需求">
              <el-row>
                <el-table :data="rowObj.bomList" class="w100">
                  <el-table-column prop="productName" label="原材料名称" align="center" />
                  <el-table-column prop="dosageQty" label="原材料总需求量" align="center">
                    <template #default="scope">
                      <div>
                        {{ scope.row.dosageQty }}
                        {{ unitFormat(scope.row.unit) }}
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column prop="currentQty" label="库存可用原材料数量" align="center">
                    <template #default="scope">
                      <div>
                        {{ scope.row.currentQty }}
                        {{ unitFormat(scope.row.unit) }}
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column prop="purchaseQty" label="需新采购原材料数量" align="center">
                    <template #default="scope">
                      <div>
                        <!-- {{ scope.row.purchaseQty }} -->
                        {{ rowObj?.prodHead?.status >= 4 ? 0 : scope.row.purchaseQty }}
                        {{ unitFormat(scope.row.unit) }}
                      </div>
                    </template>
                  </el-table-column>
                </el-table>
              </el-row>
            </el-tab-pane>
            <el-tab-pane label="工人需求">
              <h1>不满足生产需求</h1>
              <p>产线工人总需求人数：{{ rowObj?.workerList?.personPlan || 0 }}</p>
              <p>生产日期当日可上班人数：{{ rowObj?.workerList?.workerTotal || 0 }}</p>
            </el-tab-pane>
            <el-tab-pane label="设备需求">
              <eqptRequire :processes="machineList" v-if="tabActive == '4'" :disabled="true" />
            </el-tab-pane>
            <el-tab-pane label="净框需求">
              洁净筐总需求量：{{ rowObj?.boxList?.boxCount || 0 }}
            </el-tab-pane>
          </el-tabs>
        </el-col>
      </el-row>
    </el-dialog>

    <!-- 质检记录弹窗 -->
    <el-dialog v-model="inspectionVisible" title="质检记录" width="800px">
      <div class="space-y-6">
        <div class="flex items-center justify-between mb-4">
          <div class="flex items-center gap-2">
            <el-icon class="text-primary">
              <PriceTag />
            </el-icon>
            <span class="text-lg">{{ currentRecord?.productName }}</span>
          </div>
          <el-tag type="success">
            共 {{ (inspectionRecords && inspectionRecords.length) || 0 }} 次质检
          </el-tag>
        </div>
        <div v-if="!(inspectionRecords && inspectionRecords.length)" class="text-center p-8">
          暂无质检记录
        </div>
        <div v-else>
          <div v-for="(item, index) in inspectionRecords || []" :key="index">
            <div class="bg-gray-50 rounded-lg p-4">
              <div class="flex items-center justify-between mb-2">
                <span class="font-medium">检验人：{{ item.reportName }}</span>
              </div>
              <div class="space-y-2">
                <el-col :span="24">
                  <!-- <MultiImageUpload v-model="paramsInfo.reportImage" :data="{ bizType: 'contract' }" /> -->
                  <el-form-item label="报告图片">
                    <FileUpload
                      v-model="item.reportImage"
                      :showUploadBtn="false"
                      :showDelBtn="false"
                      :data="{ bizType: 'contract' }"
                      style="width: 100%"
                    />
                  </el-form-item>
                </el-col>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>

    <el-dialog
      v-model="pauseVisible"
      title="暂停生产"
      width="400px"
      @close="handleCloseDialogPause"
    >
      <el-form ref="pauseFormRef" :model="pauseFormData" label-width="100">
        <el-form-item label="备注：">
          <el-input
            v-noSpace
            v-model="pauseFormData.pauseRemark"
            type="textarea"
            maxlength="500"
            class="!w-full"
            show-word-limit
            :rows="3"
          ></el-input>
        </el-form-item>
        <el-form-item label="暂停时间：">
          <el-date-picker
            class="!w-full"
            v-model="pauseFormData.pauseTime"
            type="datetime"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            placeholder="选择日期时间"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="flex justify-end gap-2">
          <el-button @click="handleCloseDialogPause">取消</el-button>
          <el-button type="primary" @click="handleSubmitPause">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref } from "vue";
import prodOrderManageApi, {
  prodManagePageVO,
  prodOrderPageQuery,
} from "@/api/prodManage/prodOrderManage";
import { useRoute } from "vue-router";
import planOrderApi from "@/api/planManage/planOrderManage";
import prodReportManageApi from "@/api/prodRepor/prodReport";
import productBomAPI from "@/api/productBom/productBom";
import { useDateRanges } from "@/utils/useDateRanges";
import configApi, { ConfigType } from "@/api/config/config";

//暂停
const pauseFormRef = ref();
const pauseVisible = ref(false);
const pauseFormData = reactive({
  id: NaN,
  pauseRemark: "",
  pauseTime: useDateRanges().getDateTimeRange(),
});

const route = useRoute();
const queryCode = ref<string | undefined>(undefined);

const rowObj = ref();

const queryParams = reactive<prodOrderPageQuery>({
  pageNum: 1,
  pageSize: 20,
  parentCode: undefined,
  finishTime: undefined,
  statusList: [1, 3, 4, 5, 6, 7],
});

const tableData = ref<prodManagePageVO[]>();

const total = ref(0);

const filteredStatusList = ref([
  { value: 1, label: "已确认" },
  { value: 3, label: "准备中" },
  { value: 4, label: "待生产" },
  { value: 5, label: "生产中" },
  { value: 6, label: "生产完成" },
  { value: 7, label: "暂停" },
]);

//status 0 1 2 3 4
const getStatusType = (status: number) => {
  const map: Record<number, any> = {
    0: "success",
    1: "success",
    2: "warning",
    3: "info",
    4: "success",
    5: "warning",
    6: "info",
  };
  return map[status] || "info";
};
const options = ref<{ value: string; label: string }[]>([]); // 显式指定类型
const getProductType = async () => {
  try {
    const response = await productBomAPI.getTypePage({
      pageNum: 1,
      pageSize: 20,
      productType: "1",
    });
    const dataList = response?.list || [];

    options.value = dataList.map((item: any) => ({
      value: item.code,
      label: item.productName,
    }));
  } catch (error) {
    console.error("Error fetching product types:", error);
  }
};

//重置查询
const handleReset = () => {
  // queryParams = {
  //   planDate: "",
  //   productName: "",
  //   status: undefined,
  //   statusList: [],
  //   pageNum: 1,
  //   pageSize: 20,
  // };
  queryParams.status = undefined;
  queryParams.pageNum = 1;
  queryParams.pageSize = 20;
  queryParams.status = undefined;
  queryParams.statusList = [1, 3, 4, 5, 6, 7];
  queryParams.planDate = undefined;
  queryParams.finishTime = undefined;
  queryParams.productCode = undefined;
  handleQuery();
};
const loading = ref(false);
const progress = ref(0);
function handleQuery() {
  loading.value = true;

  queryParams.statusList = queryParams.status ? [Number(queryParams.status)] : [1, 3, 4, 5, 6, 7];

  console.log("queryParams", queryParams, queryParams.statusList);
  prodOrderManageApi
    .getPage({
      ...queryParams,
      status: undefined,
    })
    .then((res) => {
      let list = JSON.parse(JSON.stringify(res.list));
      list.forEach((item: any) => {
        // console.log(item.entryQty);
        item.progress = 0;
        if (item.entryQty) {
          console.log(item.entryQty / item.qty);
          if (item.status == 6) {
            item.progress = 100;
          } else {
            let num = (item.entryQty / item.qty) * 100;
            item.progress = Number(Math.floor(num).toFixed(2));
            // console.log();
          }
          if (item.progress > 100) {
            item.progress = 100;
          }
        }
      });
      console.log(list);
      tableData.value = list;
      total.value = res.total;
    })
    .catch((err) => {
      console.log(err);
      // ElMessage.error(`${err}`);
      // handleCloseDialog();
      // handleResetQuery();
    })
    .finally(() => {
      loading.value = false;
    });
}

const handleCloseDialogPause = () => {
  pauseVisible.value = false;
  pauseFormRef.value?.resetFields();
};

const handleSubmitPause = async () => {
  try {
    await prodOrderManageApi.startExecute(pauseFormData.id, {
      status: 7,
      pauseTime: pauseFormData.pauseTime,
      pauseRemark: pauseFormData.pauseRemark,
    });
    handleCloseDialogPause();
    handleQuery();
  } catch (error) {
    console.error("Error pausing production:", error);
  }
};

//暂停
function handlePause(row: any) {
  if (row.status === 5) {
    ElMessageBox.confirm("是否确认暂停？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        pauseFormData.id = row.id;
        pauseVisible.value = true;
      })
      .catch(() => {});
    return;
  }
  if (row.status == 7) {
    ElMessageBox.confirm("是否确认继续生产？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        prodOrderManageApi.startExecute(row.id, { status: 5 }).then((res) => {
          handleQuery();
        });
      })
      .catch(() => {});
    return;
  }
}

// 开始生产
function handleStartProduce(row: any) {
  console.log("开始生产", row);
  if (row.status === 5) {
    //二次确认
    ElMessageBox.confirm("是否确认完成？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        prodOrderManageApi
          .startExecute(row.id)
          .then((res) => {
            handleQuery();
          })
          .catch((err) => {
            console.log(err);
            // ElMessage.error(`${err}`);
          });
      })
      .catch(() => {});
    return;
  }
  prodOrderManageApi
    .startExecute(row.id)
    .then((res) => {
      handleQuery();
    })
    .catch((err) => {
      console.log(err);
      // ElMessage.error(`${err}`);
    });
}

const tabActive = ref("0");

//设备需求列表
const machineList = ref<any[]>([]);

// 查看详情
const rowData = ref<any[]>([]);
const dialogVisible = ref(false);
const currentRecord = ref<prodManagePageVO>();
const handleOpenDetail = async (row: any) => {
  console.log(row, "123");
  const data = await planOrderApi.getRowService(row?.id);
  dialogVisible.value = true;
  rowObj.value = { ...data };
  rowData.value = [...data?.borList];
  machineList.value = data?.machineList;
  console.log(rowObj);
  console.log(rowData);
};

// 查看检验记录
const inspectionVisible = ref(false);
const inspectionRecords = ref();

const handleOpenInspection = (row: any) => {
  inspectionVisible.value = true;
  currentRecord.value = row;
  prodReportManageApi
    .getQualityReportList({ parentCode: row?.code, pageSize: 999, pageNum: 1 })
    .then((res) => {
      res.list.forEach((item: any) => {
        console.log(item);
        let upData = [];
        if (item.reportImage) {
          upData = item.reportImage.map((item: any) => {
            return {
              name: item.split("/").pop(),
              url: item,
            };
          });
        } else {
          upData = [];
        }
        item.reportImage = JSON.parse(JSON.stringify(upData));
      });
      inspectionRecords.value = res.list;
    });
};

const handleDelete = (id: number) => {
  ElMessageBox.confirm("是否确认取消？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      prodOrderManageApi.deleteById(id).then((res) => {
        ElMessage.success("取消成功");
        handleQuery();
      });
    })
    .catch(() => {});
};

function handleCloseDialog() {
  // dialog.visible = false;
  // dialogFormDataProRef.value.resetFields();
  unitValue.value = {};
}
// 选中产品单位值
const unitValue = ref<{ label?: string; value?: string }>({});
// 单位常量列表
const unitOptions = ref<Array<{ label: string; value: string }>>([]);
const unitFormat = (unit: any) => {
  if (!unit) return;
  let unitLabel = unitOptions.value.find((item) => item.value === unit.toLowerCase())?.label;
  return unitLabel;
};
// 获取常量列表
const getUnitList = () => {
  configApi.getConfigListByType(ConfigType.Unit).then((data) => {
    unitOptions.value = data.map((item: any) => {
      return { label: item.codeName, value: item.codeValue };
    });
  });
};

onMounted(() => {
  // 获取查询参数中的 queryCode
  queryCode.value = route.query.queryCode as string | undefined;
  queryParams.parentCode = queryCode.value ? queryCode.value : "";
  //这个是MRP跳到生产单管理传的参数
  handleQuery();
  getUnitList();
});
</script>

<style scoped>
.el-input :deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}

.el-input :deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #409eff inset;
}

.el-select :deep(.el-input__wrapper) {
  box-shadow: 0 0 0 1px #dcdfe6 inset;
}

.el-select :deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #409eff inset;
}
</style>
